package files

import (
	"clouds.lgb24kcs.cn/controllers/files/request"
	"clouds.lgb24kcs.cn/errorx"
	"clouds.lgb24kcs.cn/global"
	"clouds.lgb24kcs.cn/models"
	"clouds.lgb24kcs.cn/utils"
	"clouds.lgb24kcs.cn/utils/history"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

type ObjectSearch struct {
}

var ObjectSearchAPI ObjectSearch

func (s *ObjectSearch) Search(c *gin.Context, req request.ObjectSearchReq, userId int64) {
	/*
			查询数据库
			调用sdk判断文件是否存在
		因为这个接口是在调用完加载所有文件后才调用的所以不用再去验证数据库和oss存储对象的数据一致性
	*/

	var Count int64
	//
	FileInfo := []models.Files{}
	tx := global.APP.DB.Where("bucketname=? and root_dir=? and user_id=? and filename like ?",
		req.BucketName, req.CatalogueName, userId, "%"+req.ObjectName+"%").Limit(int(req.Page)).Offset(int(req.Limit) - 1).Find(&FileInfo).Count(&Count)
	if tx.Error != nil {
		global.APP.Log.Error(tx.Error.Error())
		utils.Fail(c, errorx.ObjectSearch, tx.Error.Error())

	} else {
		filesInfoResp := []request.ObjectAllResp{}
		for _, fileinfo := range FileInfo {
			filesInfoResp = append(filesInfoResp, request.ObjectAllResp{
				//Count:         Count,
				FileLink:      fileinfo.FileLink,
				BucketName:    fileinfo.Bucketname,
				CatalogueName: fileinfo.RootDir,
				Type:          fileinfo.Type,
				ID:            int64(fileinfo.ID),
				UserId:        fileinfo.UserId,
				Size:          strconv.Itoa(int(fileinfo.Size)),
				FileName:      fileinfo.Filename,
				CreateAt:      fileinfo.CreatedAt.Format(time.DateTime),
			})
		}
		if err := history.HistoryCreate(userId, c.Request.Method, c.Request.URL.String(), c.Request.Host); err != nil {
			utils.Fail(c, errorx.ObjectSearch, err.Error())
		} else {
			utils.Success(c, Count, filesInfoResp)
		}
	}

}
